package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"time"
)

const (
	GnomeNotify = "notify-send"
	OssWebFolder = "web"
	OssLocalFolder = "home"
)

type OSSConfig struct {
	Aliyun AliyunAccount
}

type AliyunAccount struct {
	Endpoint string
	AccessKeyID string
	AccessKeySecret string
}


func main() {

	var source, folder string
	var ctxType,ext,eTag string
	_,err := os.Stat("/usr/local/oss-uploader/oss.config.json")
	ossConfig := OSSConfig{}
	isConfigFileExist := !os.IsExist(err)

	if isConfigFileExist{
		data, err := ioutil.ReadFile("/usr/local/oss-uploader/oss.config.json")
		if err != nil {
			fmt.Println(err)
			os.Exit(-1)
		}
		err = json.Unmarshal(data, &ossConfig)
		if err != nil {
			fmt.Println(err)
			os.Exit(-1)
		}
	} else {
		os.Exit(-1)
	}
	if len(os.Args) < 2 {
		fmt.Println("not enough params")
		os.Exit(-1)
	}
	source = os.Args[1]
	//source = ""
	dir, file := path.Split(source)
	//matched := regexp.MustCompile(`^(https://|http://|/*)`)
	//p := matched.ReplaceAllString(dir, "")
	//matched := regexp.MustCompile(`\?(.*)`)
	//fn := matched.ReplaceAllString(file, "")

	isHttp, _ := regexp.MatchString(`^(https|http)`, dir)
	client, err := oss.New(ossConfig.Aliyun.Endpoint, ossConfig.Aliyun.AccessKeyID, ossConfig.Aliyun.AccessKeySecret)
	if err != nil {
		_popup("create oss client failed", err.Error())
	}
	bucket, err := client.Bucket("image-smartsplus-com")
	if err != nil {
		_popup("can't get bucket information", err.Error())
	}

	if isHttp {
		folder = OssWebFolder
		client := &http.Client{}
		req,_ := http.NewRequest("GET", source, nil)
		response, err := client.Do(req)
		if err != nil {
			_popup("error", err.Error())
		} else {
			defer func(Body io.ReadCloser) {
				err := Body.Close()
				if err != nil {
					fmt.Println(err)
				}
			}(response.Body)
			ct := response.Header["Content-Type"]
			if len(ct) != 0 {
				ctxType = ct[0]
				ext = ctxType[strings.Index(ctxType,"/")+1:]
			} else {
				ext = "none"
			}

			et := response.Header["Etag"]
			if len(et)!=0 {
				eTag = et[0]
			} else {
				eTag = strconv.FormatInt(time.Now().Unix(), 10)
			}

			body, _ := ioutil.ReadAll(response.Body)
			err = bucket.PutObject(fmt.Sprintf("%s/%s.%s", folder,eTag,ext), bytes.NewReader(body))
			if err != nil {
				_popup("error", err.Error())
			} else {
				_popup("url method success", "https://image.smartsplus.com/"+OssWebFolder+"/"+eTag+"."+ext)
				fmt.Println("https://image.smartsplus.com/"+OssWebFolder+"/"+eTag+"."+ext)
			}
		}
	} else {
		folder = OssLocalFolder
		fd, err := os.Open(source)
		if err != nil {
			_popup("upload file from local machine failed", err.Error())
		}
		defer func(fd *os.File) {
			err := fd.Close()
			if err != nil {

			}
		}(fd)
		//fmt.Println(folder, eTag, ext)
		err = bucket.PutObject(fmt.Sprintf("%s/%s", folder,file), fd)
		if err != nil {
			fmt.Println(err)
			os.Exit(-1)
		}
		_popup("success", "https://image.smartsplus.com/"+OssLocalFolder+"/"+file)
		fmt.Println("https://image.smartsplus.com/"+OssLocalFolder+"/"+file)
	}
}

//
//  _popup
//  @Description: ubuntu linux popup using notify-send command
//  @param title
//  @param ctx
//
func _popup(title, ctx string) {
	var cmd string
	if runtime.GOOS == "linux" {
		cmd = GnomeNotify
	}
	err := exec.Command(cmd, title, ctx).Run()
	if err != nil {
		return
	}
}